import datetime
from flask import Flask, g, Blueprint, request, make_response
from tornado.database import Connection
import logging

pgate = Blueprint('pgate', __name__)

# Deploying with Fabric http://flask.pocoo.org/docs/patterns/fabric/
def create_app():
    app = Flask(__name__)
    
    # add converter for url matching for md5
    import md5Converter
    app.url_map.converters['md5'] = md5Converter.md5Converter

    # add 500 error handler
    app.register_error_handler('500', default_error_handler)
    app.register_error_handler('404', page_not_found)
  
    # add file logging handler
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler('trace.log', when='midnight')
    #file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

    # register the blueprint
    app.register_blueprint(pgate) 
    
    return app    

def gated(expires, max_age, content_type="text/javascript"):
    def decorator(f):
        from functools import update_wrapper 
        def gate_request(*args, **kwargs):
            resp = make_response(f(*args, **kwargs))
            resp.headers['Content-type'] = content_type
            resp.headers['Expires'] = expires
            resp.headers['Cache-Control'] = 'max-age=%s' % str(max_age)
            return resp

        return update_wrapper(gate_request, f)
    return decorator

@pgate.route("/total/<int:partner_id>/", methods=['GET'])
@gated(expires="+1h", max_age=3600)
def total(partner_id):
    return "0" 

@pgate.route("/<int:partner_id>/<md5:url>", methods=['GET'], strict_slashes=False)
@gated(expires="+7d", max_age=604800)
def access(partner_id, url):
    dbresp = g.db.get("call sp_PartnerGateLookup(%s,%s);", url, partner_id)
    resp = str(dbresp.LastOccuranceTS)
    callback = request.args.get("callback")
    if callback:
        resp = "%s(%s);\n" % (callback, resp)

    return resp

#@pgate.errorhandler(404)
def page_not_found(error):
    pgate.logger.error(error)
    return "0", 200
    #return "0", 404

# TODO: put in better logging/error handling and always return 0
#@pgate.errorhandler(500)
def default_error_handler(error):
    pgate.logger.error(error)
    return "0", 200
    #return "0", 500

@pgate.before_request
def connect_db():
    g.db = Connection("localhost", "PartnerGate_db", "root", "root")
    #g.db =yy Connection(config.DB_HOST, config.DB_NAME, config.DB_USER, config.DB_PASSWD)

@pgate.after_request
def close_connection(response):
    g.db.close()
    return response

if __name__=="__main__":
    app = create_app()
    app.run()
